package com.mioto.ld.communication.websocket.resolver;

import com.mioto.ld.communication.CommunicationCache;
import com.mioto.ld.communication.mqtt.MqttHelper;
import com.mioto.ld.communication.mqtt.protocol.model.PType;
import com.mioto.ld.communication.mqtt.protocol.model.server.DeiveClosePayload;
import com.mioto.ld.communication.websocket.model.SendCmdEnum;
import com.mioto.ld.communication.websocket.model.WsDeviceCloseBody;
import com.mioto.ld.communication.websocket.model.WsRecMessage;
import com.mioto.ld.communication.websocket.util.MessageSendUtil;
import com.mioto.ld.utils.SpringBeanUtil;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author mioto-qinxj
 * @date 2024/6/1
 * @desc 远程开关机
 */
public class WsCloseResolver implements WsMessageResolver{

    @Override
    public void resolve(ChannelHandlerContext channelHandlerContext, WsRecMessage message) {
        WsDeviceCloseBody body = ((WsDeviceCloseBody)message.getBody());
        if (MqttHelper.containsSn(body.getSn())) {
            boolean sendResult = MqttHelper.control(body.getSn(), new DeiveClosePayload(body.getPower()));
            if (sendResult) {
                SpringBeanUtil.getBean(CommunicationCache.class).put(body.getSn(), PType.SERVER_REMOTE_SHUTDOWN, message.getClientId());
            }
        }else {
            MessageSendUtil.send(channelHandlerContext.channel(), SendCmdEnum.DEVICE_OFFLINE);
        }
    }
}
